home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2005 October / PCWOCT05.iso / Software / FromTheMag / XAMPP 1.4.14 / xampp-win32-1.4.14-installer.exe / xampp / php / pear / System / Command.php
PHP Script  |  2004-03-24  |  18KB  |  546 lines

  1. <?php
  2. // {{{ license
  3.  
  4. // +----------------------------------------------------------------------+
  5. // | PHP Version 4.0                                                      |
  6. // +----------------------------------------------------------------------+
  7. // | Copyright (c) 1997-2003 The PHP Group                                |
  8. // +----------------------------------------------------------------------+
  9. // | This source file is subject to version 2.02 of the PHP license,      |
  10. // | that is bundled with this package in the file LICENSE, and is        |
  11. // | available at through the world-wide-web at                           |
  12. // | http://www.php.net/license/2_02.txt.                                 |
  13. // | If you did not receive a copy of the PHP license and are unable to   |
  14. // | obtain it through the world-wide-web, please send a note to          |
  15. // | license@php.net so we can mail you a copy immediately.               |
  16. // +----------------------------------------------------------------------+
  17. // | Author: Anders Johannsen <anders@johannsen.com>                      |
  18. // | Author: Dan Allen <dan@mojavelinux.com>
  19. // +----------------------------------------------------------------------+
  20.  
  21. // $Id: Command.php,v 1.4 2004/03/02 05:21:41 dallen Exp $
  22.  
  23. // }}}
  24. // {{{ includes
  25.  
  26. require_once 'PEAR.php';
  27. require_once 'System.php';
  28.  
  29. // }}}
  30. // {{{ constants
  31.  
  32. define('SYSTEM_COMMAND_OK',                 1);
  33. define('SYSTEM_COMMAND_ERROR',             -1);
  34. define('SYSTEM_COMMAND_NO_SHELL',          -2);
  35. define('SYSTEM_COMMAND_INVALID_SHELL',     -3);
  36. define('SYSTEM_COMMAND_TMPDIR_ERROR',      -4);
  37. define('SYSTEM_COMMAND_INVALID_OPERATOR',  -5);
  38. define('SYSTEM_COMMAND_INVALID_COMMAND',   -6);
  39. define('SYSTEM_COMMAND_OPERATOR_PLACEMENT',-7);
  40. define('SYSTEM_COMMAND_COMMAND_PLACEMENT', -8);
  41. define('SYSTEM_COMMAND_NOHUP_MISSING',     -9);
  42. define('SYSTEM_COMMAND_NO_OUTPUT',        -10);
  43. define('SYSTEM_COMMAND_STDERR',           -11);
  44.  
  45. // }}}
  46.  
  47. // {{{ class System_Command
  48.  
  49. /**
  50.  * The System_Command:: class implements an abstraction for various ways 
  51.  * of executing commands (directly using the backtick operator,
  52.  * as a background task after the script has terminated using
  53.  * register_shutdown_function() or as a detached process using nohup).
  54.  *
  55.  * @author  Anders Johannsen <anders@johannsen.com>
  56.  * @author  Dan Allen <dan@mojavelinux.com>
  57.  * @version $Revision: 1.4 $
  58.  */
  59.  
  60. // }}}
  61. class System_Command extends PEAR {
  62.     // {{{ properties
  63.  
  64.     /**
  65.      * Array of settings used when creating the shell command
  66.      *
  67.      * @var array
  68.      * @access private
  69.      */
  70.     var $options = array();
  71.  
  72.     /**
  73.      * Array of available shells to use to execute the command
  74.      *
  75.      * @var array
  76.      * @access private
  77.      */
  78.     var $shells = array();
  79.  
  80.     /**
  81.      * Array of available control operators used between commands
  82.      *
  83.      * @var array
  84.      * @access private
  85.      */
  86.     var $controlOperators = array();
  87.  
  88.     /**
  89.      * The system command to be executed
  90.      *
  91.      * @var string
  92.      * @access private
  93.      */
  94.     var $systemCommand = null;
  95.  
  96.     /**
  97.      * Previously added part to the command string
  98.      *
  99.      * @var string
  100.      * @access private
  101.      */
  102.     var $previousElement = null;
  103.  
  104.     /**
  105.      * Directory for writing stderr output
  106.      *
  107.      * @var string
  108.      * @access private
  109.      */
  110.     var $tmpDir = null;
  111.  
  112.     /**
  113.      * To allow the pear error object to accumulate when building
  114.      * the command, we use the command status to keep track when
  115.      * a pear error is raised
  116.      *
  117.      * @var int
  118.      * @access private
  119.      */
  120.     var $commandStatus = 0;
  121.         
  122.     // }}}
  123.     // {{{ constructor
  124.  
  125.     /**
  126.      * Class constructor
  127.      * 
  128.      * Defines all necessary constants and sets defaults
  129.      * 
  130.      * @access public
  131.      */
  132.     function System_Command($in_shell = null)
  133.     {
  134.         parent::PEAR();
  135.  
  136.         // Defining constants
  137.         $this->options = array(
  138.             'SEQUENCE'   => true,
  139.             'SHUTDOWN'   => false,
  140.             'SHELL'      => $this->which($in_shell),
  141.             'OUTPUT'     => true,
  142.             'NOHUP'      => false,
  143.             'BACKGROUND' => false,
  144.         );
  145.  
  146.         // prepare the available control operators
  147.         $this->controlOperators = array(
  148.             'PIPE'  => '|',
  149.             'AND'   => '&&',
  150.             'OR'    => '||',
  151.             'GROUP' => ';',
  152.             'LFIFO' => '<',
  153.             'RFIFO' => '>',
  154.         );
  155.                 
  156.         // List of allowed/available shells
  157.         $this->shells = array(
  158.             'sh',
  159.             'bash',
  160.             'zsh',
  161.             'tcsh',
  162.             'csh',
  163.             'ash',
  164.             'sash',
  165.             'esh',
  166.             'ksh'
  167.         );
  168.                                    
  169.         // Find the first available shell
  170.         if (empty($this->options['SHELL'])) {
  171.             foreach ($this->shells as $shell) {
  172.                 if ($this->options['SHELL'] = $this->which($shell)) {
  173.                     break;
  174.                 }
  175.             }
  176.  
  177.             // see if we still have no shell
  178.             if (empty($this->options['SHELL'])) {
  179.                 $this = PEAR::raiseError(null, SYSTEM_COMMAND_NO_SHELL, null, E_USER_WARNING, null, 'System_Command_Error', true);
  180.                 return;
  181.             }
  182.         }
  183.  
  184.         // Caputre a temporary directory for capturing stderr from commands
  185.         $this->tmpdir = System::tmpdir();
  186.         if (!System::mkDir("-p {$this->tmpdir}")) {
  187.             $this = PEAR::raiseError(null, SYSTEM_COMMAND_TMPDIR_ERROR, null, E_USER_WARNING, null, 'System_Command_Error', true);
  188.             return;
  189.         }
  190.     }
  191.         
  192.     // }}}
  193.     // {{{ setOption()
  194.  
  195.     /**
  196.      * Sets any option
  197.      * 
  198.      * The options are currently:
  199.      * SEQUENCE : Allow a sequence command or not (right now this is always on)
  200.      * SHUTDOWN : Execute commands via a shutdown function 
  201.      * SHELL    : Path to shell
  202.      * OUTPUT   : Output stdout from process
  203.      * NOHUP    : Use nohup to detach process
  204.      * BACKGROUND : Run as a background process with &
  205.      *
  206.      * @param $in_option is a constant, which corresponds to the
  207.      *                option that should be changed
  208.      * @param $in_setting is the value of the option currently
  209.      *                 being toggled.
  210.      * @access public
  211.      * @return bool true if succes, else false
  212.      */
  213.     function setOption($in_option, $in_setting)
  214.     {
  215.         $option = strtoupper($in_option);
  216.  
  217.         if (empty($this->options[$option])) {
  218.             PEAR::raiseError(null, SYSTEM_COMMAND_ERROR, null, E_USER_NOTICE, null, 'System_Command_Error', true);
  219.             return false;
  220.         }
  221.                 
  222.         switch ($option) {
  223.             case 'OUTPUT':
  224.             case 'SHUTDOWN':
  225.             case 'SEQUENCE':
  226.             case 'BACKGROUND':
  227.                 $this->options[$option] = !empty($in_setting);
  228.                 return true;
  229.             break;
  230.                 
  231.             case 'SHELL':
  232.                 if (($shell = $this->which($in_setting)) !== false) {
  233.                     $this->options[$option] = $shell;
  234.                     return true;
  235.                 } 
  236.                 else {
  237.                     PEAR::raiseError(null, SYSTEM_COMMAND_NO_SHELL, null, E_USER_NOTICE, $in_setting, 'System_Command_Error', true);
  238.                     return false;
  239.                 }
  240.             break;
  241.                         
  242.             case 'NOHUP':
  243.                 if (empty($in_setting)) {
  244.                     $this->options[$option] = false;
  245.                 } 
  246.                 else if ($location = $this->which('nohup')) {
  247.                     $this->options[$option] = $location;
  248.                 } 
  249.                 else {
  250.                     PEAR::raiseError(null, SYSTEM_COMMAND_NOHUP_MISSING, null, E_USER_NOTICE, null, 'System_Command_Error', true);
  251.                     return false;
  252.                 }
  253.             break;
  254.         }
  255.     }
  256.     
  257.     // }}}
  258.     // {{{ pushCommand()
  259.  
  260.     /**
  261.      * Used to push a command onto the running command to be executed
  262.      *
  263.      * @param  string $in_command binary to be run
  264.      * @param  string $in_argument either an option or argument value, to be handled appropriately
  265.      * @param  string $in_argument
  266.      * @param  ...
  267.      *
  268.      * @access public
  269.      * @return boolean true on success {or System_Command_Error Exception}
  270.      */
  271.     function pushCommand($in_command)
  272.     {
  273.         if (!is_null($this->previousElement) && !in_array($this->previousElement, $this->controlOperators)) {
  274.             $this->commandStatus = -1;
  275.             $error = PEAR::raiseError(null, SYSTEM_COMMAND_COMMAND_PLACEMENT, null, E_USER_WARNING, null, 'System_Command_Error', true);
  276.         }
  277.  
  278.         // check for error here
  279.         $command = escapeshellcmd($this->which($in_command));
  280.         if ($command === false) {
  281.             $error = PEAR::raiseError(null, SYSTEM_COMMAND_INVALID_COMMAND, null, E_USER_WARNING, null, 'System_Command_Error', true);
  282.         }
  283.  
  284.         $argv = func_get_args();
  285.         array_shift($argv);
  286.         foreach($argv as $arg) {
  287.             if (strpos($arg, '-') === 0) {
  288.                 $command .= ' ' . $arg; 
  289.             }
  290.             elseif ($arg != '') {
  291.                 $command .= ' ' . escapeshellarg($arg);
  292.             }
  293.         }
  294.  
  295.         $this->previousElement = $command;
  296.         $this->systemCommand .= $command;
  297.  
  298.         return isset($error) ? $error : true;
  299.     }
  300.  
  301.     // }}}
  302.     // {{{ pushOperator()
  303.  
  304.     /**
  305.      * Used to push an operator onto the running command to be executed
  306.      *
  307.      * @param  string $in_operator Either string reprentation of operator or system character
  308.      *
  309.      * @access public
  310.      * @return boolean true on success {or System_Command_Error Exception}
  311.      */
  312.     function pushOperator($in_operator)
  313.     {
  314.         $operator = isset($this->controlOperators[$in_operator]) ? $this->controlOperators[$in_operator] : $in_operator;
  315.  
  316.         if (is_null($this->previousElement) || in_array($this->previousElement, $this->controlOperators)) {
  317.             $this->commandStatus = -1;
  318.             $error = PEAR::raiseError(null, SYSTEM_COMMAND_OPERATOR_PLACEMENT, null, E_USER_WARNING, null, 'System_Command_Error', true);
  319.         }
  320.         elseif (!in_array($operator, $this->controlOperators)) {
  321.             $this->commandStatus = -1;
  322.             $error = PEAR::raiseError(null, SYSTEM_COMMAND_INVALID_OPERATOR, null, E_USER_WARNING, $operator, 'System_Command_Error', true);
  323.         }
  324.  
  325.         $this->previousElement = $operator;
  326.         $this->systemCommand .= ' ' . $operator . ' ';
  327.         return isset($error) ? $error : true;
  328.     }
  329.  
  330.     // }}}
  331.     // {{{ execute()
  332.  
  333.     /**
  334.      * Executes the code according to given options
  335.      *
  336.      * @return bool true if success {or System_Command_Exception}
  337.      *
  338.      * @access public
  339.      */
  340.     function execute() 
  341.     {
  342.         // if the command is empty or if the last element was a control operator, we can't continue
  343.         if (is_null($this->previousElement) || $this->commandStatus == -1 || in_array($this->previousElement, $this->controlOperators)) {
  344.             return PEAR::raiseError(null, SYSTEM_COMMAND_INVALID_COMMAND, null, E_USER_WARNING, $this->systemCommand, 'System_Command_Error', true);
  345.         }
  346.  
  347.         // Warning about impossible mix of options
  348.         if (!empty($this->options['OUTPUT'])) {
  349.             if (!empty($this->options['SHUTDOWN']) || !empty($this->options['NOHUP'])) {
  350.                 return PEAR::raiseError(null, SYSTEM_COMMAND_NO_OUTPUT, null, E_USER_WARNING, null, 'System_Command_Error', true);
  351.             }
  352.         }
  353.                 
  354.         // if this is not going to stdout, then redirect to /dev/null
  355.         if (empty($this->options['OUTPUT'])) {
  356.             $this->systemCommand .= ' >/dev/null';
  357.         }
  358.                 
  359.         $suffix = '';
  360.         // run a command immune to hangups, with output to a non-tty
  361.         if (!empty($this->options['NOHUP'])) {
  362.             $this->systemCommand = $this->options['NOHUP'] . $this->systemCommand;
  363.         }
  364.         // run a background process (only if not nohup)
  365.         elseif (!empty($this->options['BACKGROUND'])) {
  366.             $suffix = ' &';
  367.         }
  368.                 
  369.         // Register to be run on shutdown
  370.         if (!empty($this->options['SHUTDOWN'])) {
  371.             $line = "system(\"{$this->systemCommand}$suffix\");";
  372.             $function = create_function('', $line);
  373.             register_shutdown_function($function);
  374.             return true;
  375.         } 
  376.         else {
  377.             // send stderr to a file so that we can reap the error message
  378.             $tmpFile = tempnam($this->tmpDir, 'System_Command-');
  379.             $this->systemCommand .= ' 2>' . $tmpFile . $suffix;
  380.             $shellPipe = $this->which('echo') . ' ' . escapeshellarg($this->systemCommand) . ' | ' . $this->options['SHELL'];
  381.             exec($shellPipe, $result, $returnVal);
  382.  
  383.             if ($returnVal !== 0) {
  384.                 $error = implode('', file($tmpFile));
  385.                 $return = PEAR::raiseError(null, SYSTEM_COMMAND_STDERR, null, E_USER_WARNING, null, 'System_Command_Error', true);
  386.             }
  387.             else {
  388.                 $return = implode("\n", $result);
  389.             }
  390.  
  391.             unlink($tmpFile);
  392.             return $return;
  393.         }
  394.     }
  395.  
  396.     // }}}
  397.     // {{{ which()
  398.  
  399.     /**
  400.      * Functionality similiar to unix 'which'. Searches the path
  401.      * for the specified program. 
  402.      *
  403.      * @param $cmd name of the executable to search for 
  404.      *
  405.      * @access private
  406.      * @return string returns the full path if found, false if not
  407.      */
  408.     function which($in_cmd)
  409.     {
  410.         // if we already have a binary, then return it
  411.         if (is_executable($in_cmd)) {
  412.             return $in_cmd;
  413.         }
  414.  
  415.         $paths = explode(':', $_ENV['PATH']);
  416.             
  417.         foreach ($paths as $path) {
  418.             $location = $path . '/' . $in_cmd;
  419.                             
  420.             if (is_executable($location)) {
  421.                 return $location;
  422.             }
  423.         }
  424.  
  425.         return false;
  426.     }   
  427.  
  428.     // }}}
  429.     // {{{ reset()
  430.  
  431.     /**
  432.      * Prepare for a new command to be built
  433.      *
  434.      * @access public
  435.      * @return void
  436.      */
  437.     function reset()
  438.     {
  439.         $this->previousElement = null;
  440.         $this->systemCommand = null;
  441.         $this->commandStatus = 0;
  442.     }
  443.  
  444.     // }}}
  445.     // {{{ errorMessage()
  446.  
  447.     /**
  448.      * Return a textual error message for a System_Command error code
  449.      *
  450.      * @param integer error code
  451.      *
  452.      * @return string error message, or false if the error code was
  453.      * not recognized
  454.      */
  455.     function errorMessage($in_value)
  456.     {
  457.         static $errorMessages;
  458.         if (!isset($errorMessages)) {
  459.             $errorMessages = array(
  460.                 SYSTEM_COMMAND_OK                     => 'no error',
  461.                 SYSTEM_COMMAND_ERROR                  => 'unknown error',
  462.                 SYSTEM_COMMAND_NO_SHELL               => 'no shell found',
  463.                 SYSTEM_COMMAND_INVALID_SHELL          => 'invalid shell',
  464.                 SYSTEM_COMMAND_TMPDIR_ERROR           => 'could not create temporary directory',
  465.                 SYSTEM_COMMAND_INVALID_OPERATOR       => 'control operator invalid',
  466.                 SYSTEM_COMMAND_INVALID_COMMAND        => 'invalid system command',
  467.                 SYSTEM_COMMAND_OPERATOR_PLACEMENT     => 'invalid placement of control operator',
  468.                 SYSTEM_COMMAND_COMMAND_PLACEMENT      => 'invalid placement of command',
  469.                 SYSTEM_COMMAND_NOHUP_MISSING          => 'nohup not found on system',
  470.                 SYSTEM_COMMAND_NO_OUTPUT              => 'output not allowed',
  471.                 SYSTEM_COMMAND_STDERR                 => 'command wrote to stderr',
  472.             );
  473.         }
  474.  
  475.         if (System_Command::isError($in_value)) {
  476.             $in_value = $in_value->getCode();
  477.         }
  478.  
  479.         return isset($errorMessages[$in_value]) ? $errorMessages[$in_value] : $errorMessages[SYSTEM_COMMAND_ERROR];
  480.     }
  481.  
  482.     // }}}
  483.     // {{{ isError()
  484.  
  485.     /**
  486.      * Tell whether a result code from a System_Command method is an error
  487.      *
  488.      * @param int result code
  489.      *
  490.      * @return bool whether $in_value is an error
  491.      *
  492.      * @access public
  493.      */
  494.     function isError($in_value)
  495.     {
  496.         return (is_object($in_value) &&
  497.                 (strtolower(get_class($in_value)) == 'system_command_error' ||
  498.                  is_subclass_of($in_value, 'system_command_error')));
  499.     }
  500.     
  501.     // }}}
  502. }
  503.  
  504. // {{{ class System_Command_Error
  505.  
  506. /**
  507.  * System_Command_Error constructor.
  508.  *
  509.  * @param mixed      System_Command error code, or string with error message.
  510.  * @param integer    what "error mode" to operate in
  511.  * @param integer    what error level to use for $mode & PEAR_ERROR_TRIGGER
  512.  * @param mixed      additional debug info, such as the last query
  513.  *
  514.  * @access public
  515.  *
  516.  * @see PEAR_Error
  517.  */
  518.  
  519. // }}}
  520. class System_Command_Error extends PEAR_Error
  521. {
  522.     // {{{ properties
  523.  
  524.     /**
  525.      * Message in front of the error message
  526.      * @var string $error_message_prefix
  527.      */
  528.     var $error_message_prefix = 'System_Command Error: ';
  529.  
  530.     // }}}
  531.     // {{{ constructor
  532.  
  533.     function System_Command_Error($code = SYSTEM_COMMAND_ERROR, $mode = PEAR_ERROR_RETURN,
  534.               $level = E_USER_NOTICE, $debuginfo = null)
  535.     {
  536.         if (is_int($code)) {
  537.             $this->PEAR_Error(System_Command::errorMessage($code), $code, $mode, $level, $debuginfo);
  538.         } else {
  539.             $this->PEAR_Error("Invalid error code: $code", SYSTEM_COMMAND_ERROR, $mode, $level, $debuginfo);
  540.         }
  541.     }
  542.     
  543.     // }}}
  544. }
  545. ?>
  546.